// useMultiProcRequest.js
import { ref, getCurrentInstance } from 'vue'

export function useMultiProcRequest() {
  const { proxy } = getCurrentInstance()
  const loading = ref(false)
  const results = ref([])
  const router = useRouter()
  const route = useRoute()

  const formatToMinSecMs = (totalMilliseconds, flag = false) => {
    if (totalMilliseconds == 0) {
      return 0
    }

    const minutes = Math.floor(totalMilliseconds / 60000)
    const seconds =
      Math.floor((totalMilliseconds % 60000) / 1000) < 10
        ? '0' + Math.floor((totalMilliseconds % 60000) / 1000)
        : Math.floor((totalMilliseconds % 60000) / 1000)
    const hundredMs = Math.floor((totalMilliseconds % 1000) / 100)
    if (flag) {
      return `${minutes}'${seconds}''`
    }
    return `${minutes}'${seconds}''${hundredMs}`
  }

  const formatToFixed2 = (num) => {
    if (typeof num !== 'number') return '0.00'
    if (num == 0) return 0
    const str = num.toString()
    const index = str.indexOf('.')
    if (index === -1) return str + '.00'
    return str.substring(0, index + 3).padEnd(index + 3, '0')
  }

  const gotoUrl = (name, newQuery = {}) => {
    if (name) {
      const currentQuery = route.query.params
      const isSameQuery = JSON.stringify(currentQuery) === JSON.stringify(newQuery)

      router
        .push({
          name: name,
          query: newQuery,
        })
        .then(() => {
          // if (!isSameQuery) {
          //   // 强制刷新
          //   window.location.reload()
          // }
        })
    }
  }

  const fetchForProcs = async (procList, params = {}) => {
    loading.value = true
    try {
      const { t, ...restParams } = params?.keyValues
      const requestPar = {
        procName: params?.procName,
        keyValues: restParams,
      }
      const res = await Promise.all(
        procList.map((proc) => proxy.$postJson('/apiFets/execProc', requestPar))
      )
      results.value = res[0]?.result || []
      return results
    } catch (e) {
      console.error('并行请求失败', e)
      throw e
    } finally {
      loading.value = false
    }
  }

  const fecthString = async (nameStr, len = 10) => {
    if (nameStr && nameStr.length >= len) {
      return nameStr.substring(0, len) + '...'
    }
    return nameStr
  }

  return {
    formatToFixed2,
    formatToMinSecMs,
    gotoUrl,
    results,
    fetchForProcs,
    fecthString,
  }
}
